package com.sendpo.zjx.sendpo.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchatsDomain;
import com.sendpo.zjx.sendpo.fragment.storeallproduce.AllProduceFragment;
import com.sendpo.zjx.sendpo.fragment.storeallproduce.SendActiveFragment;
import com.sendpo.zjx.sendpo.fragment.storeallproduce.StoreAllProduceBaseFragment;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.shizhefei.view.viewpager.SViewPager;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.imagewatcher.ImageWatcher;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by Administrator on 2017/8/19.
 */

public class StoreMainAllProduceActivity extends AppCompatActivity implements ImageWatcher.OnPictureLongPressListener,AMapLocationListener {
    @BindView(R.id.indicator)
    ScrollIndicatorView indicator;
    @BindView(R.id.viewpager)
    SViewPager viewpager;
    public static String[] titles = new String[]{"全部商品", "发表动态"};

    @BindView(R.id.touxiang_cir)
    CircleImageView touxiangCir;
    @BindView(R.id.uname)
    TextView uname;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.collapsingtoolbarlayout)
    CollapsingToolbarLayout collapsingtoolbarlayout;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    private IndicatorViewPager indicatorViewPager;
    @BindView(value = R.id.head_bg)
    public ImageView head_bg;
    @BindView(R.id.v_image_watcher)
    public ImageWatcher vImageWatcher;
    BottomDialog bottomDialog;
    public Tencent tencent = null;

//    public int id=0;
    public   int merchantsId=0;
    public AmapLocationService amapLocationService;
    public double userLongitude = 0;
    public double userLatitude = 0;
    public String userProvince = "";
    public String userCity = "";
    public String userArea = "";
    public String userAddress = "";
    @BindView(value = R.id.swiperefresh)
    public SwipeRefreshLayout swiperefresh;
    private AllProduceFragment allproduce;
    private SendActiveFragment sendactive;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_allproduce);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                   if(verticalOffset!=0){
                       swiperefresh.setEnabled(false);
                   }else{
                       swiperefresh.setEnabled(true);
                   }
            }
        });
        swiperefresh.setColorSchemeColors(getResources().getColor(R.color.default_theme));
        swiperefresh.setProgressViewOffset(false, 0, DensityUtil.dip2px(150));
        swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                query(merchantsId+"");
                if(allproduce!=null){
                    allproduce.pagenow=1;
                    allproduce.query(allproduce.pagenow);
                }

            }
        });
        amapLocationService=new AmapLocationService(this);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(this);
        amapLocationService.start();
        query(merchantsId+"");

    }

    public AMapLocationClientOption getDefaultAmapLocationOptions(){
        AMapLocationClientOption mLocationOption=null;
        if(mLocationOption==null){
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(2000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return  mLocationOption;
    }
    private void initComponent() {
        vImageWatcher.setTranslucentStatus(0); // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
        vImageWatcher.setErrorImageRes(R.mipmap.error_picture); // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
        vImageWatcher.setOnPictureLongPressListener(this); // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
        initData();
    //    id=getIntent().getIntExtra("id",0);
         merchantsId=getIntent().getIntExtra("merchantsId",0);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @OnClick({R.id.backbt, R.id.share_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.share_bt:
                bottomDialog.show();
                break;

        }
    }

    public void initShare() {
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View qqsapce = v.findViewById(R.id.qqspace_bt);
                qqsapce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        shareToQzone();
                    }
                });
                View qq_bt = v.findViewById(R.id.qq_bt);
                qq_bt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onClickQQShare();
                    }
                });

                View exit = v.findViewById(R.id.closebt);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.layout_dialog_share);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");
        tencent = Tencent.createInstance(HttpUrl.QQ_KEY, getApplicationContext());

    }

    public void initData() {
        viewpager.setCanScroll(false);
        viewpager.setOffscreenPageLimit(1);
        indicatorViewPager = new IndicatorViewPager(indicator, viewpager);
        List<StoreAllProduceBaseFragment> fragments = new ArrayList<>();
        fragments.add(allproduce=new AllProduceFragment());
        fragments.add(sendactive=new SendActiveFragment());
        indicatorViewPager.setAdapter(new FragmentIndicatorAdapter(getSupportFragmentManager(), fragments));
        indicatorViewPager.setClickIndicatorAnim(true);
        //点击切换颜色
        indicatorViewPager.setIndicatorOnTransitionListener(new OnTransitionTextListener().setColor(getResources().getColor(R.color.default_theme), getResources().getColor(R.color.default_gray)));
        //颜色块
        ColorBar colorBar = new ColorBar(this, getResources().getColor(R.color.default_theme), 5);
        colorBar.setWidth(120);
        indicatorViewPager.setIndicatorScrollBar(colorBar);
        initShare();
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }



    public void query(final String id) {
        swiperefresh.setRefreshing(true);
        String cache_result= Tools.getCache(StoreMainAllProduceActivity.this, HttpUrl.querymeychantsidmerchant+id);
        Gson gson=new Gson();
        if(cache_result!=null&&!cache_result.equals("")){
            MerchatsDomain domain = gson.fromJson(cache_result, MerchatsDomain.class);
            switch (domain.getState()) {
                case HttpCode.SUCCESS:
                    Glide.with(StoreMainAllProduceActivity.this)
                            .load("" + domain.getData().getMerchantsAvatarpath())
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .centerCrop()
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                    touxiangCir.setImageBitmap(resource);
                                }
                            });
                    Glide.with(StoreMainAllProduceActivity.this)
                            .load("" + domain.getData().getMerchantsBgpath())
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .centerCrop()
                            .into(head_bg);
                    uname.setText(domain.getData().getMerchantsName()+"");
                    break;
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("merchantsId",id+"");
        Xutils.POST(HttpUrl.querymeychantsidmerchant, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                swiperefresh.setRefreshing(false);
                Gson gson = new Gson();
                MerchatsDomain domain = gson.fromJson(result, MerchatsDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        Tools.setCache(StoreMainAllProduceActivity.this, HttpUrl.querymeychantsidmerchant+""+id,result);
                        Glide.with(StoreMainAllProduceActivity.this)
                                .load("" + domain.getData().getMerchantsAvatarpath())
                                .asBitmap()
                                .animate(R.anim.fade_in)
                                .placeholder(getResources().getColor(R.color.default_lightgray))
                                .centerCrop()
                                .into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                        touxiangCir.setImageBitmap(resource);
                                    }
                                });
                        Glide.with(StoreMainAllProduceActivity.this)
                                .load("" + domain.getData().getMerchantsBgpath())
                                .asBitmap()
                                .animate(R.anim.fade_in)
                                .placeholder(getResources().getColor(R.color.default_lightgray))
                                .centerCrop()
                                .into(head_bg);
                        uname.setText(domain.getData().getMerchantsName()+"");
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                swiperefresh.setRefreshing(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (amapLocationService == null || aMapLocation == null) {
            Toast.makeText(getApplicationContext(),"定位失败，请检查网络和手机权限或者是否打开GPS",Toast.LENGTH_SHORT).show();
            return;
        }
        userLongitude=aMapLocation.getLongitude();
        userLatitude=aMapLocation.getLatitude();
        userProvince=aMapLocation.getProvince();
        userCity=aMapLocation.getCity();
        userArea=aMapLocation.getDistrict();
        int index=aMapLocation.getAddress().lastIndexOf(userProvince+userCity+userArea);
        userAddress=aMapLocation.getAddress().substring(index+(userProvince+userCity+userArea).length(),aMapLocation.getAddress().length());
    }


    private class FragmentIndicatorAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {
        private List<StoreAllProduceBaseFragment> fragments;

        public FragmentIndicatorAdapter(FragmentManager fragmentManager, List<StoreAllProduceBaseFragment> fragments) {
            super(fragmentManager);
            this.fragments = fragments;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = View.inflate(StoreMainAllProduceActivity.this, R.layout.tab_focus, null);
            }
            TextView textView = (TextView) convertView;
            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            textView.setText(titles[position]);
            return textView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {
            return fragments.get(position);
        }
    }


    //QQ腾讯好友分享
    private void onClickQQShare() {

        Bundle data = new Bundle();
        data.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        data.putString(QQShare.SHARE_TO_QQ_TITLE, "产品标题");
        data.putString(QQShare.SHARE_TO_QQ_SUMMARY, "产品描述");
        data.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://www.baidu.com");
        data.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
                "http://images.3158.cn/data/attachment/tougao/article/2015/12/17/df0b92921cb9fa8bb4f82c18ad1e08ba.jpg");
        data.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        data.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        tencent.shareToQQ(this, data, new QQShareUiListener());
    }

    //QQ分享监听
    private class QQShareUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
            System.out.println("********" + o.toString());

        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext().getApplicationContext(), uiError.errorDetail, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {

        }
    }


    //QQ腾讯分享空间
    private void shareToQzone() {
//分享类型
        Bundle params = new Bundle();
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "产品标题");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "产品描述");
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "http://wapi.jiechennuo.com/wifijz.apk");
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        ArrayList<String> strings = new ArrayList<String>();
        strings.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491909596292&di=8d177470e12744ff9eba0f7f55a89c78&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201611%2F2016120301.jpg");
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, strings);
        tencent.shareToQzone(this, params, new QQShareUiListener());
    }
}
